package com.infore.common.utils;

import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {

	private  static  RequestConfig config = null;
	private static final int TIMEOUT = 100000;
	
	static {

		// 设置网络超时
		config = RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT).setConnectTimeout(TIMEOUT)
				.setSocketTimeout(TIMEOUT).build();
	}
	
	
	/**
	 * post请求
	 * @param map
	 * @param url
	 * @return
	 */
	public static String httpPost(Map<String, Object> map, String url,Map<String,String> headers) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (String key : map.keySet()) {
				params.add(new BasicNameValuePair(key, map.get(key).toString()));
			}
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(config);
		httpPost.setEntity(entity);

		//设置header
		if (headers != null && headers.size() > 0) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httpPost.setHeader(entry.getKey(),entry.getValue());
			}
		}

		CloseableHttpResponse response = null;
		String ret ="";
		try {
			response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity retentity = response.getEntity();
			    ret = EntityUtils.toString(retentity, Consts.UTF_8);
			}else{
				System.out.println(response);
				System.out.println(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if(httpclient!=null){
					httpclient.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		System.out.println(ret);
		return ret;
	}
	
	public static String httpPostString(Map<String, String> map, String url) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (String key : map.keySet()) {
				params.add(new BasicNameValuePair(key, map.get(key).toString()));
			}
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(config);
		httpPost.setEntity(entity);
//		httpPost.setHeader("Content-type", "application/json; charset=utf-8");
		httpPost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
		CloseableHttpResponse response = null;
		String ret ="";
		try {
			response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity retentity = response.getEntity();
				ret = EntityUtils.toString(retentity, Consts.UTF_8);
			}else{
				System.out.println(response);
				System.out.println(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if(httpclient!=null){
					httpclient.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
//		System.out.println(ret);
		return ret;
	}
	
	/**
	 * httppost 发送json数据
	 * 
	 */
	public static String sendHttpPost(String url, String body) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Content-type", "application/json; charset=utf-8");
//		httpPost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
		httpPost.setConfig(config);
		CloseableHttpResponse response = null;
		String ret ="";
		try {
			//不设置编码 中文查询会没有返回结果
			StringEntity requestEntity = new StringEntity(body, "UTF-8");
			requestEntity.setContentType(ContentType.APPLICATION_JSON.toString());
			httpPost.setEntity(requestEntity);
			response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity retentity = response.getEntity();
			    ret = EntityUtils.toString(retentity, Consts.UTF_8);
			}else{
				System.out.println(response);
				System.out.println(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if(httpclient!=null){
					httpclient.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
//		System.out.println(ret);
		return ret;
		
	}
	public static String httpGet(Map<String, Object> map, String url,Map<String, Object> headers) {
		// 设置网络超时
		RequestConfig config = RequestConfig.custom()
				.setConnectionRequestTimeout(50 * 1000)
				.setConnectTimeout(50 * 1000)
				.setSocketTimeout(50 * 1000).build();
		CloseableHttpClient httpclient = HttpClients.createDefault();

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (String key : map.keySet()) {
				params.add(new BasicNameValuePair(key, map.get(key).toString()));
			}
		}

		try {
			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
//			System.out.println(url);
		} catch (ParseException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		HttpGet httpGet=new HttpGet(url);
		httpGet.setConfig(config);
		httpGet.setHeader("Content-type", "application/json; charset=utf-8");
		if (headers != null && !headers.isEmpty()) {
			for (String key : headers.keySet()) {
				httpGet.setHeader(key,headers.get(key).toString());
			}
		}
		CloseableHttpResponse response = null;
		String ret ="";
		try {
			response = httpclient.execute(httpGet);

			System.err.println("xxx"+response);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity retentity = response.getEntity();
				ret = EntityUtils.toString(retentity, Consts.UTF_8);
			}else{
				System.out.println(response);
				System.out.println(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if(httpclient!=null){
					httpclient.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
//		System.out.println(ret);
		return ret;
	}
	public static String httpGet(Map<String, Object> map, String url) {
		// 设置网络超时
		RequestConfig config = RequestConfig.custom()
				.setConnectionRequestTimeout(50 * 1000)
				.setConnectTimeout(50 * 1000)
				.setSocketTimeout(50 * 1000).build();
		CloseableHttpClient httpclient = HttpClients.createDefault();
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (String key : map.keySet()) {
				params.add(new BasicNameValuePair(key, map.get(key).toString()));
			}
		}
		
		try {
			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
//			System.out.println(url);
		} catch (ParseException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		HttpGet httpGet=new HttpGet(url);
		httpGet.setConfig(config);
		httpGet.setHeader("Content-type", "application/json; charset=utf-8");
//		httpGet.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
		CloseableHttpResponse response = null;
		String ret ="";
		try {
			response = httpclient.execute(httpGet);
			
			System.err.println("xxx"+response);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity retentity = response.getEntity();
				ret = EntityUtils.toString(retentity, Consts.UTF_8);
			}else{
				System.out.println(response);
				System.out.println(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if(httpclient!=null){
					httpclient.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
//		System.out.println(ret);
		return ret;
	}
	public static String httpGetString(Map<String, String> map, String url) {
		// 设置网络超时
		RequestConfig config = RequestConfig.custom()
				.setConnectionRequestTimeout(10 * 1000)
				.setConnectTimeout(10 * 1000)
				.setSocketTimeout(10 * 1000).build();
		CloseableHttpClient httpclient = HttpClients.createDefault();
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if (map != null && !map.isEmpty()) {
			for (String key : map.keySet()) {
				params.add(new BasicNameValuePair(key, map.get(key).toString()));
			}
		}
		
		try {
			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
			System.out.println(url);
		} catch (ParseException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		HttpGet httpGet=new HttpGet(url);
		httpGet.setConfig(config);
		httpGet.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
		CloseableHttpResponse response = null;
		String ret ="";
		try {
			response = httpclient.execute(httpGet);
			
//			System.err.println("xxx"+response);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity retentity = response.getEntity();
				ret = EntityUtils.toString(retentity, Consts.UTF_8);
			}else{
				System.out.println(response);
				System.out.println(EntityUtils.toString(response.getEntity(), Consts.UTF_8));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if(httpclient!=null){
					httpclient.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
//		System.out.println(ret);
		return ret;
	}
	
	
	public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            
            OutputStreamWriter outr = new OutputStreamWriter(conn.getOutputStream(),"utf-8");
            out = new PrintWriter(outr);
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
	/**
	 * 发送 http post 请求，参数以原生字符串进行提交
	 * @param url
	 * @param encode
	 * @return
	 */
	public static String httpPostRaw(String url, String stringJson, Map<String,String> headers, String encode){
		if(encode == null){
			encode = "utf-8";
		}
		//HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		HttpPost httpost = new HttpPost(url);

		//设置header
		httpost.setHeader("Content-type", "application/json");
		if (headers != null && headers.size() > 0) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httpost.setHeader(entry.getKey(),entry.getValue());
			}
		}
		//组织请求参数
		StringEntity stringEntity = new StringEntity(stringJson, encode);
		httpost.setEntity(stringEntity);
		String content = null;
		CloseableHttpResponse  httpResponse = null;
		try {
			//响应信息
			httpResponse = closeableHttpClient.execute(httpost);
			HttpEntity entity = httpResponse.getEntity();
			content = EntityUtils.toString(entity, encode);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				httpResponse.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {  //关闭连接、释放资源
			closeableHttpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * 发送 http put 请求，参数以原生字符串进行提交
	 * @param url
	 * @param encode
	 * @return
	 */
	public static String httpPutRaw(String url,String stringJson,Map<String,String> headers, String encode){
		if(encode == null){
			encode = "utf-8";
		}
		//HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		HttpPut httpput = new HttpPut(url);

		//设置header
		httpput.setHeader("Content-type", "application/json");
		if (headers != null && headers.size() > 0) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httpput.setHeader(entry.getKey(),entry.getValue());
			}
		}
		//组织请求参数
		StringEntity stringEntity = new StringEntity(stringJson, encode);
		httpput.setEntity(stringEntity);
		String content = null;
		CloseableHttpResponse  httpResponse = null;
		try {
			//响应信息
			httpResponse = closeableHttpClient.execute(httpput);
			HttpEntity entity = httpResponse.getEntity();
			content = EntityUtils.toString(entity, encode);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				httpResponse.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			closeableHttpClient.close();  //关闭连接、释放资源
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	/**
	 * 发送http delete请求
	 */
	public static String httpDelete(String url,Map<String,String> headers,String encode){
		if(encode == null){
			encode = "utf-8";
		}
		String content = null;
		//since 4.3 不再使用 DefaultHttpClient
		CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
		HttpDelete httpdelete = new HttpDelete(url);
		//设置header
		if (headers != null && headers.size() > 0) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				httpdelete.setHeader(entry.getKey(),entry.getValue());
			}
		}
		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = closeableHttpClient.execute(httpdelete);
			HttpEntity entity = httpResponse.getEntity();
			content = EntityUtils.toString(entity, encode);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				httpResponse.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {   //关闭连接、释放资源
			closeableHttpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
/*	public static void main(String[] args) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("juid", "1");
		String url = "http://192.168.7.32/recommend/getRecommendListArticle";
		httpGet(params, url);
	}*/

}
